package com.devmarvel.creditcardentry.fields;

import com.devmarvel.creditcardentry.ResourceTable;
import com.devmarvel.creditcardentry.internal.CreditCardUtil;
import com.devmarvel.creditcardentry.library.CardType;
import ohos.agp.components.AttrSet;
import ohos.agp.render.Paint;
import ohos.agp.utils.Rect;
import ohos.app.Context;

public class SecurityCodeText extends CreditEntryFieldBase {

    private CardType type;

    private int length;

    private String mHelperText;

    public SecurityCodeText(Context context) {
        super(context);
        init();
    }

    public SecurityCodeText(Context context, AttrSet attrs) {
        super(context, attrs);
        init();
    }

    public SecurityCodeText(Context context, AttrSet attrs, String defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    void init() {
        super.init();
        setHint("CVV");
        Paint textPaint = new Paint();
        textPaint.setTextSize(getTextSize());
        Rect bounds = textPaint.getTextBounds("MMM");
        setMinWidth(bounds.getWidth() + (2 * HORIZONTAL_PADDING) + PADDING_OFFSET);
        setMinHeight(bounds.getHeight());
    }

    /* TextWatcher Implementation Methods */
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    public void afterTextChanged(String s) {
        if (type == null) {
            watcherEnabled = false;
            this.setText("");
            watcherEnabled = true;
        }
    }

    public void formatAndSetText(String s) {
        setText(s);
    }

    public void textChanged(CharSequence s, int start, int before, int count) {
        if (type != null) {
            if (s.length() >= length) {
                setValid(true);
                String remainder = null;
                if (s.length() > length()) remainder = String.valueOf(s).substring(length);
                watcherEnabled = false;
                setText(String.valueOf(s).substring(0, length));
                watcherEnabled = true;
                delegate.onSecurityCodeValid(remainder);
            } else {
                setValid(false);
            }
        }
    }

    @SuppressWarnings("unused")
    public CardType getType() {
        return type;
    }

    public void setType(CardType type) {
        this.type = type;
        this.length = CreditCardUtil.securityCodeValid(type);
    }

    @Override
    public void setHelperText(String helperText) {
        mHelperText = helperText;
    }

    @Override
    public String getHelperText() {
        return (mHelperText != null ? mHelperText : context.getString(ResourceTable.String_SecurityCodeHelp));
    }
}
